package com.weiz.rabbitmq.task;

import com.weiz.rabbitmq.constant.Constans;
import com.weiz.rabbitmq.entity.MessageLog;
import com.weiz.rabbitmq.entity.OrderInfo;
import com.weiz.rabbitmq.mapper.MessageLogMapper;
import com.weiz.rabbitmq.producer.RabbitOrderSender;
import com.weiz.rabbitmq.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class RetryMessageTasker {
    private static Logger logger = LoggerFactory.getLogger(RetryMessageTasker.class);
    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Autowired
    private MessageLogMapper messageLogMapper;

    /**
     * 定时任务
     */
    @Scheduled(initialDelay = 10000, fixedDelay = 10000)
    public void reSend(){
        logger.info("开始重发消息");
        //抽取消息状态为0且已经超时的消息集合
        List<MessageLog> list = messageLogMapper.query4StatusAndTimeoutMessage();
        list.forEach(messageLog -> {
            //投递三次以上的消息
            if(messageLog.getTryCount() >= 3){
                //更新失败的消息
                messageLogMapper.changeMessageLogStatus(messageLog.getMessageId(), Constans.ORDER_SEND_FAILURE, new Date());
            } else {
                // 重试投递消息，将重试次数递增
                messageLogMapper.update4ReSend(messageLog.getMessageId(),  new Date());
                OrderInfo reSendOrder = JsonUtil.jsonToObject(messageLog.getMessage(), OrderInfo.class);
                try {
                    rabbitOrderSender.sendOrder(reSendOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("异常处理"+e.getStackTrace());
                }
            }
        });
        logger.info("消息重发结束");
    }
}
